package io.sundial.console.datasource.service;

import io.sundial.console.Pagination;
import io.sundial.console.datasource.core.Datasource;
import io.sundial.console.datasource.dao.DatasourceRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 数据源服务接口实现
 *
 * @author Payne 646742615@qq.com
 * 2019/1/3 16:21
 */
@Service
@Transactional(readOnly = true)
public class DatasourceServiceBean implements DatasourceService {

    @Resource
    private DatasourceRepository datasourceRepository;

    @Override
    public Datasource find(String name) {
        return datasourceRepository.getOne(name);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void save(Datasource datasource) {
        datasourceRepository.save(datasource);
    }

    @Override
    public Pagination<Datasource> search(int pageNo, int pageSize, String keyword) {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.by(Sort.Order.desc("dateCreated")));
        Page<Datasource> page = datasourceRepository.search("%" + (keyword != null ? keyword : "") + "%", pageable);
        return new Pagination<>(page.getTotalElements(), page.getContent());
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void shift(String name, boolean disabled) {
        if (disabled) {
            datasourceRepository.disable(name);
        } else {
            datasourceRepository.enable(name);
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void remove(String name) {
        datasourceRepository.delete(name);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void update(String name, Datasource datasource) {
        datasourceRepository.update(
                name,
                datasource.getType(),
                datasource.getAddress(),
                datasource.getCatalog(),
                datasource.getUsername(),
                datasource.getPassword(),
                datasource.getDescription(),
                new Date()
        );
    }
}
